package org.example.filter;

import io.jsonwebtoken.Claims;
import org.example.common.JwtUtil;
import org.example.security.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class TokenFilter extends OncePerRequestFilter {

    @Autowired
    CustomUserDetailsService userDetailsService;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token =request.getHeader("access_token");
        if(token==null){
            //放行
            filterChain.doFilter(request, response);
            request.setAttribute("error_msg","登录失败");
            return;
        }
        Claims claims = null;
        try {
            claims = JwtUtil.parseJWT(token);
            String username = claims.getSubject();

            if(StringUtils.isEmpty(username)){
                //用户名为空，未登录
                throw new RuntimeException("用户未登录");
            }
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        //放行
        filterChain.doFilter(request, response);
    }
}
